<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>现代BBS评论系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        neutral: '#64748B',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .comment-shadow {
                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            }
            .reply-line {
                border-left: 2px solid #e2e8f0;
            }
            .btn-hover {
                @apply transition-all duration-200 hover:shadow-lg transform hover:-translate-y-0.5;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-dark">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-comments text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-primary">现代BBS评论系统</h1>
            </div>
            <div class="flex items-center space-x-4">
                {% if current_user %}
                    <span class="text-gray-700">欢迎，{{ current_user.username }}</span>
                    <a href="/logout" class="text-neutral hover:text-primary transition-colors">
                        <i class="fa fa-sign-out mr-1"></i>退出登录
                    </a>
                {% else %}
                    <a href="/login" class="text-neutral hover:text-primary transition-colors">
                        <i class="fa fa-sign-in mr-1"></i>登录
                    </a>
                    <a href="/register" class="bg-primary text-white px-3 py-1.5 rounded-lg hover:bg-primary/90 transition-colors">
                        注册
                    </a>
                {% endif %}
                <button id="themeToggle" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-moon-o text-neutral"></i>
                </button>
            </div>
        </div>
    </header>
    
    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8 max-w-4xl">
        <!-- 介绍区 -->
        <section class="mb-10 text-center">
            <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-4">欢迎参与讨论</h2>
            <p class="text-neutral max-w-2xl mx-auto">在这里分享你的想法，参与有意义的讨论，尊重他人观点，共同维护友好的交流环境。</p>
        </section>
        
        <!-- 评论表单（仅登录用户显示） -->
        {% if current_user %}
            <section class="bg-white rounded-xl p-6 shadow-md mb-10 transform transition-all hover:shadow-lg">
                <h3 class="text-xl font-semibold mb-4 flex items-center text-gray-800">
                    <i class="fa fa-pencil-square-o text-primary mr-2"></i>发表评论
                </h3>
                <form id="commentForm" class="space-y-4">
                    <input type="hidden" id="authorId" value="{{ current_user.id }}">
                    <input type="hidden" id="parentId" value="">
                    
                    <!-- 1. 文字内容（原有） -->
                    <div>
                        <label for="content" class="block text-sm font-medium text-gray-700 mb-1">评论内容</label>
                        <textarea 
                            id="content" 
                            rows="4" 
                            required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all outline-none resize-none text-gray-800"
                            placeholder="分享你的想法..."
                        ></textarea>
                    </div>

                    <!-- 2. 新增：图片上传控件 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            上传图片（最多{{ MAX_UPLOAD_IMAGES }}张，单张不超过5MB）
                        </label>
                        <input 
                            type="file" 
                            id="imageUpload" 
                            name="images"   
                            multiple         
                            accept="image/jpeg,image/png,image/gif"  
                            class="w-full text-gray-700 border border-gray-300 rounded-lg px-4 py-2"  
                            style="display: none;"
                        >
                        <!-- 自定义选择文件按钮（可选，解决原生按钮丑的问题，避免代码外露） -->
                        <label for="imageUpload" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 cursor-pointer">
                            <i class="fa fa-upload mr-2"></i>选择文件
                        </label>
                        <span id="fileSelectedText" class="ml-3 text-sm text-gray-500">未选择文件</span>
                    </div>

                    <!-- 3. 新增：已选图片预览区 -->
                    <div id="imagePreview" class="flex flex-wrap gap-3 mt-2 hidden">
                        <!-- 预览图会通过JS动态添加 -->
                    </div>

                    <!-- 4. 提交按钮（原有） -->
                    <button 
                        type="submit" 
                        class="bg-primary text-white px-6 py-2.5 rounded-lg font-medium btn-hover flex items-center"
                    >
                        <i class="fa fa-paper-plane mr-2"></i>发布评论
                    </button>
                </form>
            </section>
        {% else %}
            <section class="bg-white rounded-xl p-6 shadow-md mb-10 text-center">
                <p class="text-neutral mb-4">请先<a href="/login" class="text-primary hover:underline">登录</a>或<a href="/register" class="text-primary hover:underline">注册</a>后发表评论</p>
                <a href="/login" class="inline-block bg-primary text-white px-6 py-2.5 rounded-lg font-medium btn-hover">
                    去登录
                </a>
            </section>
        {% endif %}
        
        <!-- 评论列表 -->
        <section>
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-xl font-semibold flex items-center">
                    <i class="fa fa-comments-o text-primary mr-2"></i>评论列表
                </h3>
                <span id="commentCount" class="bg-gray-100 text-neutral px-3 py-1 rounded-full text-sm">{{ comments|length }} 条评论</span>
            </div>
            
            <div id="commentsContainer" class="space-y-6">
                <!-- 加载状态 -->
                <div id="loadingIndicator" class="flex justify-center py-10 hidden">
                    <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary"></div>
                </div>
                
                <!-- 空状态 -->
                {% if comments|length == 0 %}
                    <div id="emptyState" class="text-center py-16">
                        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                            <i class="fa fa-comment-o text-2xl text-gray-400"></i>
                        </div>
                        <h3 class="text-lg font-medium text-gray-900 mb-1">暂无评论</h3>
                        <p class="text-neutral">成为第一个发表评论的人吧！</p>
                    </div>
                {% else %}
                    <!-- 循环渲染顶级评论 -->
                    {% for top_comment in comments if top_comment.parent_id == None %}
                        <!-- 传递当前评论到子模板 -->
                        {% with comment=top_comment %}
                            {% include "comment_item.html" %}
                        {% endwith %}
                    {% endfor %}
                {% endif %}
            </div>
        </section>
    </main>
    
    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 mt-16">
        <div class="container mx-auto px-4 py-8 text-center text-neutral">
            <p>© 2025 现代BBS评论系统</p>
        </div>
    </footer>
    
    <!-- 通知组件 -->
    <div id="notification" class="fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50"></div>


    <!-- 编辑评论模态框 -->
<div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 w-full max-w-md">
        <h3 class="text-xl font-semibold mb-4">编辑评论</h3>
        <form id="editForm">
            <input type="hidden" id="editCommentId">
            <div>
                <textarea 
                    id="editContent" 
                    rows="4" 
                    required
                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all outline-none resize-none"
                ></textarea>
            </div>

            <!-- 新增：图片上传区域 -->
            <div class="mt-4">
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    图片（最多{{ MAX_UPLOAD_IMAGES }}张，单张不超过5MB）
                </label>
                <input 
                    type="file" 
                    id="editImageUpload" 
                    name="images"   
                    multiple         
                    accept="image/jpeg,image/png,image/gif"  
                    class="w-full text-gray-700 border border-gray-300 rounded-lg px-4 py-2"  
                    style="display: none;"
                >
                <label for="editImageUpload" class="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 cursor-pointer">
                    <i class="fa fa-upload mr-2"></i>添加图片
                </label>
                <span id="editFileSelectedText" class="ml-3 text-sm text-gray-500">未选择文件</span>
            </div>
            
            <!-- 新增：已上传图片预览区 -->
            <div id="editImagePreview" class="flex flex-wrap gap-3 mt-2"></div>


            <div class="mt-4 flex justify-end space-x-3">
                <button type="button" id="cancelEdit" onclick="handleCancelClick()" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors">
                    取消
                </button>
                <button type="submit" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors">
                    保存修改
                </button>
            </div>
        </form>
    </div>
</div>


<!-- 新增：图片预览模态框 -->
<div id="imagePreviewModal" class="fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 hidden">
    <button id="closePreviewModal" class="absolute top-4 right-4 text-white text-2xl hover:text-gray-300 transition-colors">
        <i class="fa fa-times"></i>
    </button>
    <img id="previewImage" src="" alt="高清图片预览" class="max-w-[90%] max-h-[90vh] object-contain">
</div>



    <script>
        // API基础URL
        const API_BASE_URL = '';
        
        // DOM元素
        const commentForm = document.getElementById('commentForm');
        const commentsContainer = document.getElementById('commentsContainer');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const emptyState = document.getElementById('emptyState');
        const commentCount = document.getElementById('commentCount');
        const notification = document.getElementById('notification');
        const themeToggle = document.getElementById('themeToggle');
        const currentUserId = {{ current_user.id if current_user else null }};
        
        // 初始化
        // 初始化（删除模板语法判断，直接加载评论）
document.addEventListener('DOMContentLoaded', () => {
    loadComments(); // 无需判断模板变量，直接调用加载函数
    setupEventListeners();
});
        
        // 事件监听
        function setupEventListeners() {
            if (commentForm) {
                commentForm.addEventListener('submit', handleCommentSubmit);
            }
            themeToggle.addEventListener('click', toggleTheme);
            
            // 回复按钮事件
            document.querySelectorAll('.reply-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const commentId = btn.dataset.commentId;
                    const authorName = btn.dataset.authorName;
                    replyTo(commentId, authorName);
                });
            });
        



            // 【新增】编辑按钮监听（兼容动态元素）
    // 方法：监听父容器（commentsContainer），再定位到.edit-btn
    commentsContainer.addEventListener('click', (e) => {
        const editBtn = e.target.closest('.edit-btn');
        if (editBtn) {
            const commentId = editBtn.dataset.commentId;
            
            // 找到对应的评论元素，获取原始内容（处理<br>转义）
            const commentElement = document.querySelector(`[data-id="${commentId}"]`);
            // 根据你的HTML结构，评论内容在class为text-gray-800的p标签中
            const contentElement = commentElement.querySelector('p.text-gray-800');            
            // 将<br>转回换行符，确保编辑框内容格式正确
            const originalContent = contentElement.innerHTML.replace(/<br>/g, '\n');
            
            // 填充编辑表单
            document.getElementById('editCommentId').value = commentId;
            document.getElementById('editContent').value = originalContent;
            

            // 清空预览区和删除记录
            editImagePreview.innerHTML = '';
            deletedImageUrls = [];
            
            // 加载现有图片
            const comment = comments.find(c => c.id == commentId);
            if (comment && comment.image_urls && comment.image_urls.length > 0) {
                comment.image_urls.forEach((imgUrl, index) => {
                    const thumbUrl = comment.thumbnail_urls[index];
                    const previewItem = document.createElement('div');
                    previewItem.className = 'relative w-24 h-24 rounded-md overflow-hidden border-2 border-gray-300';
                    previewItem.dataset.type = 'existing';
                    previewItem.dataset.url = imgUrl;
                    
                    const img = document.createElement('img');
                    img.src = thumbUrl;
                    img.className = 'w-full h-full object-cover';
                    
                    const deleteBtn = document.createElement('button');
                    deleteBtn.className = 'absolute top-1 right-1 bg-black bg-opacity-50 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-opacity-70 transition-colors';
                    deleteBtn.innerHTML = '<i class="fa fa-times"></i>';
                    deleteBtn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        // 将删除的图片URL加入记录
                        deletedImageUrls.push(imgUrl);
                        previewItem.remove();
                    });
                    
                    previewItem.appendChild(img);
                    previewItem.appendChild(deleteBtn);
                    editImagePreview.appendChild(previewItem);
                });
            }


            // 显示编辑模态框
            document.getElementById('editModal').classList.remove('hidden');
        }

        const deleteBtn = e.target.closest('.delete-btn');
        // if (deleteBtn) {
        //     const commentId = deleteBtn.dataset.commentId;
        //     const authorId = parseInt(deleteBtn.dataset.authorId);
        //     if (currentUserId === authorId) {
        //         deleteComment(commentId);
        //     } else {
        //         showNotification('没有权限删除他人评论', 'warning');
        //     }
        // }
    });


            // 修改编辑表单提交处理
            document.getElementById('editForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                
                const commentId = document.getElementById('editCommentId').value;
                // 确保获取的是评论内容文本框的值
                const content = document.getElementById('editContent').value.trim();
                
                if (!content) {
                    return showNotification('请输入评论内容', 'warning');
                }
                
                try {
                    showLoading();
                    

                    // 使用FormData来处理文字和图片
                    // 提交时，正确添加删除的图片URL
                    const formData = new FormData();
                    formData.append('content', content); // 必须添加内容，不能为空

                    // 关键：删除的图片URL列表，用同一个key多次添加
                    deletedImageUrls.forEach(url => {
                        formData.append('deleted_images', url); // 直接重复使用'deleted_images'作为key
                    });
                    // deletedImageUrls.forEach((url, index) => {
                    //     formData.append(`deleted_images[${index}]`, url);
                    // });

                    // 添加新上传的图片
                    if (editImageUpload.files && editImageUpload.files.length > 0) {
                        const validFiles = Array.from(editImageUpload.files).slice(0, MAX_UPLOAD_IMAGES);
                        validFiles.forEach(file => {
                            formData.append('images', file);
                        });
                    }


                    const response = await fetch(`${API_BASE_URL}/comments/${commentId}`, {
                        method: 'PUT',
                        // headers: {
                        //     'Content-Type': 'application/json',
                        // },
                        // // 确保只传递content字段，不要包含author相关字段
                        // body: JSON.stringify({ content: content }),
                        body: formData, // 直接传递 FormData，而非 JSON
                        credentials: 'include'
                    });
                    
                    if (!response.ok) {
                        const error = await response.json();
                        throw new Error(error.detail || '修改失败');
                    }
                    
                    // 重新加载评论
                    loadComments();
                    document.getElementById('editModal').classList.add('hidden');
                    document.getElementById('editForm').reset(); // 重置表单
                    editImagePreview.innerHTML = '';
                    deletedImageUrls = [];
                    showNotification('评论修改成功', 'success');
                    
                } catch (error) {
                    console.error('修改评论时出错:', error);
                    // // 新增：获取并打印服务器返回的详细错误信息
                    // if (error.response) {
                    //     error.response.json().then(errData => {
                    //         console.log('服务器错误详情:', errData); // 重点查看这里的detail字段
                    //     });
                    // }
                    // showNotification(error.message || '修改失败，请稍后重试', 'error');
                    
                    // 关键修改：正确解析服务器返回的错误详情
                    if (error.response) {
                        try {
                            const errData = await error.response.json();
                            console.log('服务器返回的详细错误:', errData);
                            
                            // 提取错误信息并显示
                            let errorMessage = '修改失败: ';
                            if (errData.detail && Array.isArray(errData.detail)) {
                                // FastAPI的验证错误通常是detail数组
                                errorMessage += errData.detail.map(item => {
                                    // 显示字段名和错误原因，例如："deleted_images: 不是有效的列表"
                                    return `${item.loc.join('.')}: ${item.msg}`;
                                }).join('; ');
                            } else {
                                errorMessage += errData.detail || '数据格式错误';
                            }
                            showNotification(errorMessage, 'error');
                        } catch (parseError) {
                            // 如果解析JSON失败
                            showNotification('修改失败，服务器返回格式错误', 'error');
                        }
                    } else {
                        showNotification(error.message || '修改失败，请稍后重试', 'error');
                    }

                } finally {
                    hideLoading();
                }
            });


            // 将原有的取消按钮事件监听替换为
// document.addEventListener('DOMContentLoaded', () => {
//     // 1. 取消编辑按钮逻辑（核心修复）
//     const cancelEditBtn = document.getElementById('cancelEdit');
//     if (cancelEditBtn) {
//         cancelEditBtn.addEventListener('click', () => {
//             const editModal = document.getElementById('editModal');
//             const editForm = document.getElementById('editForm');
//             if (editModal) editModal.classList.add('hidden'); // 隐藏模态框
//             if (editForm) editForm.reset(); // 重置编辑表单
//         });
//     }

//     // 2. 模态框外部点击关闭逻辑（保留，增强体验）
//     const editModal = document.getElementById('editModal');
//     if (editModal) {
//         editModal.addEventListener('click', (e) => {
//             if (e.target === editModal) { // 仅点击背景时关闭
//                 editModal.classList.add('hidden');
//                 const editForm = document.getElementById('editForm');
//                 if (editForm) editForm.reset();
//             }
//         });
//     }
// });

// 修复编辑模态框关闭功能
document.addEventListener('DOMContentLoaded', () => {
    const editModal = document.getElementById('editModal');
    const cancelEditBtn = document.getElementById('cancelEdit');
    const editForm = document.getElementById('editForm');
    const editImagePreview = document.getElementById('editImagePreview');
    
    // 存储删除的图片URL列表
    let deletedImageUrls = [];

    // 取消按钮取消按钮点击事件
    if (cancelEditBtn && editModal) {
        // cancelEditBtn.addEventListener('click', () => {
        cancelEditBtn.onclick = function() {
            editModal.classList.add('hidden');
            if (editForm) editForm.reset();
            if (editImagePreview) editImagePreview.innerHTML = '';
            deletedImageUrls = []; // 重置删除记录
            console.log('取消按钮被点击'); // 用于测试是否触发
        };
    }
    

    // // 点击模态框外部关闭
    // if (editModal) {
    //     editModal.addEventListener('click', (e) => {
    //         // 检查点击的是模态框背景（不是内容区）
    //         if (e.target === editModal) {
    //             editModal.classList.add('hidden');
    //             const editForm = document.getElementById('editForm');
    //         const editImagePreview = document.getElementById('editImagePreview');
    //             if (editForm) editForm.reset();
    //             if (editImagePreview) editImagePreview.innerHTML = '';
    //             deletedImageUrls = []; // 重置删除记录
    //         }
    //     });
    // }

    // 确保关闭预览模态框功能正常
    const imagePreviewModal = document.getElementById('imagePreviewModal');
    const closePreviewModal = document.getElementById('closePreviewModal');
    if (imagePreviewModal && closePreviewModal) {
        closePreviewModal.addEventListener('click', () => {
            imagePreviewModal.classList.add('hidden');
        });
    }
});
            
            // 同时确保模态框点击外部可以关闭（可选增强）
            document.getElementById('editModal').addEventListener('click', (e) => {
                if (e.target === document.getElementById('editModal')) {
                    document.getElementById('editModal').classList.add('hidden');
                    document.getElementById('editForm').reset();
                }
            });


            // 删除按钮事件
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    const commentId = btn.dataset.commentId;
                    const authorId = parseInt(btn.dataset.authorId);
                    if (currentUserId === authorId) {
                        deleteComment(commentId);
                    } else {
                        showNotification('没有权限删除他人评论', 'warning');
                    }
                });
            });
        }


        // 全局取消按钮处理函数
function handleCancelClick() {
    const editModal = document.getElementById('editModal');
    const editForm = document.getElementById('editForm');
    const editImagePreview = document.getElementById('editImagePreview');
    
    if (editModal) editModal.classList.add('hidden');
    if (editForm) editForm.reset();
    if (editImagePreview) editImagePreview.innerHTML = '';
    
    // 重置删除记录（如果有这个变量）
    window.deletedImageUrls = [];
    console.log('取消按钮点击生效');
}

        // 加载评论
       // 确保在页面加载时获取评论数据
let comments = []; // 先初始化变量

// 1. 加载评论（更新为正确逻辑）
async function loadComments() {
    try {
        showLoading();
        // 携带 session cookie，确保后端识别登录状态
        const response = await fetch(`${API_BASE_URL}/comments`, {
            credentials: 'include'
        });
        
        if (!response.ok) throw new Error(`加载失败，状态码: ${response.status}`);
        
        const commentsData = await response.json();
        comments = commentsData; // 更新全局数组
        renderComments(commentsData); // 调用渲染函数
        updateCommentCount(commentsData.length); // 更新评论数
        
        hideLoading();
    } catch (error) {
        console.error('加载评论出错:', error);
        showNotification('加载评论失败，请稍后重试', 'error');
        hideLoading();
        checkEmptyState(true); // 加载失败显示空状态
    }
}

// 页面加载完成后调用
document.addEventListener('DOMContentLoaded', () => {
                
            loadComments();
            setupEventListeners();
        });

        /*
        // 渲染评论
        function renderComments(comments) {

            commentsContainer.innerHTML = '';
            const topLevelComments = comments.filter(comment => comment.parent_id === null);
            
            if (topLevelComments.length === 0) {
                checkEmptyState(true);
                return;
            }
            
            topLevelComments.forEach(comment => {
                const commentElement = createCommentElement(comment, comments);
                commentsContainer.appendChild(commentElement);
            });
            setupEventListeners();
        }
        
function renderComments() {
  const commentList = document.getElementById('comment-list');
  if (!commentList) return;
  
  commentList.innerHTML = '';
  
  // 确保使用的是已经初始化的comments变量
  comments.forEach(comment => {
    // 渲染单个评论的逻辑
    const commentElement = document.createElement('div');
    commentElement.className = 'comment';
    commentElement.innerHTML = `
      <h4>${comment.author}</h4>
      <p>${comment.content}</p>
      <small>${new Date(comment.created_at).toLocaleString()}</small>
    `;
    commentList.appendChild(commentElement);
  });
}

*/



// 2. 渲染评论（整合逻辑，渲染到正确容器）
function renderComments(commentsData) {
    commentsContainer.innerHTML = ''; // 清空容器
    const topLevelComments = commentsData.filter(c => c.parent_id === null); // 筛选顶级评论
    
    if (topLevelComments.length === 0) {
        checkEmptyState(true); // 无评论显示空状态
        return;
    }
    
    checkEmptyState(false); // 有评论隐藏空状态
    // 渲染所有顶级评论
    topLevelComments.forEach(comment => {
        const commentElement = createCommentElement(comment, commentsData);
        commentsContainer.appendChild(commentElement);
    });
    setupEventListeners(); // 重新绑定按钮事件（动态元素需重新绑定）
}


        function createCommentElement(comment, allComments) {
    const div = document.createElement('div');
    div.className = 'bg-white rounded-xl p-6 comment-shadow transition-all duration-300 hover:shadow-lg';
    div.dataset.id = comment.id;
    
    // 判断是否为顶级评论和当前用户是否为作者
    const isTopLevel = comment.parent_id === null; // 顶级评论判断
    const isAuthor = currentUserId === comment.author_id; // 作者判断
    
    const formattedDate = new Date(comment.created_at).toLocaleString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
    
    const formattedContent = comment.content.replace(/\n/g, '<br>');
    
    // 构建删除按钮（原有逻辑）
    const deleteBtn = isAuthor 
        ? `<button class="delete-btn text-neutral hover:text-red-500 p-1.5 rounded-full hover:bg-gray-100 transition-colors" 
                   data-comment-id="${comment.id}" 
                   data-author-id="${comment.author_id}"
                   title="删除">
               <i class="fa fa-trash-o"></i>
           </button>` 
        : '';
    
    // 构建修改按钮（新增逻辑：仅顶级评论的作者可见）
    const editBtn = isTopLevel && isAuthor
        ? `<button class="edit-btn text-neutral hover:text-blue-500 p-1.5 rounded-full hover:bg-gray-100 transition-colors"
                  data-comment-id="${comment.id}"
                  title="修改">
              <i class="fa fa-pencil"></i>
          </button>`
        : '';
    
    div.innerHTML = `
        <div class="flex justify-between items-start mb-3">
            <div class="flex items-center">
                <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold mr-3">
                    ${comment.author.charAt(0).toUpperCase()}
                </div>
                <div>
                    <h4 class="font-medium text-gray-800">${comment.author}</h4>
                    <p class="text-sm text-neutral">${formattedDate}</p>
                </div>
            </div>
            <div class="flex space-x-2">
                <button class="reply-btn text-neutral hover:text-primary p-1.5 rounded-full hover:bg-gray-100 transition-colors"
                        data-comment-id="${comment.id}"
                        data-author-name="${comment.author}"
                        title="回复">
                    <i class="fa fa-reply"></i>
                </button>
                ${editBtn} <!-- 插入修改按钮 -->
                ${deleteBtn} <!-- 原有删除按钮 -->
            </div>
        </div>
        <div class="mb-4">
            <p class="text-gray-800">${formattedContent}</p>
        </div>
        <div class="replies pl-6 mt-4 space-y-4"></div>
    `;
    
    // 添加回复
    const repliesContainer = div.querySelector('.replies');
    const replies = allComments.filter(c => c.parent_id === comment.id);
    
    replies.forEach(reply => {
        const replyElement = createCommentElement(reply, allComments);
        replyElement.classList.add('reply-line');
        repliesContainer.appendChild(replyElement);
    });
    
    return div;
}

       // 提交评论
// 处理评论提交（修复：提交成功后重新渲染评论，无需手动刷新）
async function handleCommentSubmit(e) {
    e.preventDefault();
    
    // 首先检查登录状态（前端双重校验）
    if (!currentUserId) {
        return showNotification('请先登录后再发表评论', 'warning');
    }
    
    const contentInput = document.getElementById('content');
    const parentIdInput = document.getElementById('parentId');
    
    const commentData = {
        content: contentInput.value.trim(),
        parent_id: parentIdInput.value ? parseInt(parentIdInput.value) : null
    };
    
    if (!commentData.content) {
        return showNotification('请输入评论内容', 'warning');
    }
    
    try {
        showLoading();
        
        const response = await fetch(`${API_BASE_URL}/comments`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                // 如需携带认证信息（如JWT），这里需要添加
                // 'Authorization': `Bearer ${getToken()}`
            },
            body: JSON.stringify(commentData),
            // 确保跨域请求携带认证信息
            credentials: 'include'
        });
        
        // 重点：区分不同错误状态码
        if (!response.ok) {
            if (response.status === 401) {
                // 未授权：登录状态失效
                return showNotification('登录状态已失效，请重新登录', 'error');
            } else if (response.status === 400) {
                // 请求参数错误
                const error = await response.json();
                return showNotification(error.detail || '评论内容不符合要求', 'error');
            } else {
                throw new Error('服务器错误，提交评论失败');
            }
        }
        
        // 提交成功：先重新获取所有评论
        const newCommentsRes = await fetch(`${API_BASE_URL}/comments`, { credentials: 'include' });
        if (!newCommentsRes.ok) throw new Error('获取最新评论失败');
        const newComments = await newCommentsRes.json();
        
        // 再处理UI更新（现在newComments已正确定义）
        commentForm.reset();
        parentIdInput.value = '';
        renderComments(newComments);
        updateCommentCount(newComments.length);
        checkEmptyState(newComments.length === 0);
        showNotification(commentData.parent_id ? '回复成功！' : '评论发表成功！', 'success');

    } catch (error) {
        console.error('提交评论时出错:', error);
        showNotification(error.message || '网络异常，请稍后重试', 'error');
    } finally {
        hideLoading();
    }
}
    


        // 回复功能
        function replyTo(commentId, authorName) {
            const parentIdInput = document.getElementById('parentId');
            const contentInput = document.getElementById('content');
            
            parentIdInput.value = commentId;
            contentInput.value = `@${authorName} `;
            contentInput.focus();
            commentForm.scrollIntoView({ behavior: 'smooth' });
        }
        
        // 删除评论
        async function deleteComment(commentId) {
            if (!confirm('确定要删除这条评论吗？')) {
                return;
            }
            
            try {


                

                const response = await fetch(`${API_BASE_URL}/comments/${commentId}`, {
                    method: 'DELETE',

                    // 新增：携带认证信息
                    credentials: 'include'// 确保携带cookie
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.detail || '删除失败');
                }
                
                // 优化：不刷新页面，直接重新加载评论
                loadComments();
                // window.location.reload();

                showNotification('评论已删除', 'success');
                
            } catch (error) {
                console.error('删除评论时出错:', error);
                showNotification(error.message || '删除失败，请稍后重试', 'error');
            }
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            let bgColor, textColor, icon;
            switch (type) {
                case 'success':
                    bgColor = 'bg-green-500';
                    textColor = 'text-white';
                    icon = 'fa-check-circle';
                    break;
                case 'error':
                    bgColor = 'bg-red-500';
                    textColor = 'text-white';
                    icon = 'fa-exclamation-circle';
                    break;
                case 'warning':
                    bgColor = 'bg-yellow-500';
                    textColor = 'text-white';
                    icon = 'fa-exclamation-triangle';
                    break;
                default:
                    bgColor = 'bg-primary';
                    textColor = 'text-white';
                    icon = 'fa-info-circle';
            }
            
            notification.className = `fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-0 opacity-100 transition-all duration-300 flex items-center z-50 ${bgColor} ${textColor}`;
            notification.innerHTML = `<i class="fa ${icon} mr-2"></i> ${message}`;
            
            setTimeout(() => {
                notification.className = 'fixed bottom-4 right-4 px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50';
            }, 3000);
        }
        
        // 加载状态控制
        function showLoading() {
            loadingIndicator.classList.remove('hidden');
            if (emptyState) emptyState.classList.add('hidden');
        }
        function hideLoading() {
            loadingIndicator.classList.add('hidden');
        }
        function checkEmptyState(isEmpty) {
            if (emptyState) {
                emptyState.classList.toggle('hidden', !isEmpty);
            }
        }
        
        // 更新评论计数
        function updateCommentCount(count) {
            if (commentCount) commentCount.textContent = `${count} 条评论`;
        }
        
        // 主题切换
        function toggleTheme() {
            document.body.classList.toggle('bg-gray-900');
            document.body.classList.toggle('bg-gray-50');
            document.body.classList.toggle('text-white');
            document.body.classList.toggle('text-dark');
            
            const icon = themeToggle.querySelector('i');
            icon.classList.toggle('fa-moon-o');
            icon.classList.toggle('fa-sun-o');
        }
    </script>



    <script>
                // -------------------------- 新增：全局变量 --------------------------
        const imageUpload = document.getElementById('imageUpload');
        const fileSelectedText = document.getElementById('fileSelectedText');

        const imagePreview = document.getElementById('imagePreview');
        const imagePreviewModal = document.getElementById('imagePreviewModal');
        const previewImage = document.getElementById('previewImage');
        const closePreviewModal = document.getElementById('closePreviewModal');
        const MAX_UPLOAD_IMAGES = {{ MAX_UPLOAD_IMAGES }};  // 从后端获取最大上传数量（需Jinja2渲染）

        const editImageUpload = document.getElementById('editImageUpload');
        const editFileSelectedText = document.getElementById('editFileSelectedText');
        const editImagePreview = document.getElementById('editImagePreview');
        let deletedImageUrls = []; // 记录要删除的图片URL

        if (imageUpload && fileSelectedText) {
            imageUpload.addEventListener('change', (e) => {
                const files = e.target.files;
                if (files && files.length > 0) {
                    const filenames = Array.from(files).map(f => f.name).join(', ');
                    fileSelectedText.textContent = `已选择：${filenames}`;
                } else {
                    fileSelectedText.textContent = '未选择文件';
                }
            });
        }


        // -------------------------- 新增：1. 图片上传预览逻辑 --------------------------
        if (imageUpload) {
            imageUpload.addEventListener('change', (e) => {
                const files = e.target.files;
                imagePreview.innerHTML = '';  // 清空原有预览
                
                if (!files || files.length === 0) {
                    imagePreview.classList.add('hidden');
                    return;
                }

                // 限制预览数量（与后端一致）
                const validFiles = Array.from(files).slice(0, MAX_UPLOAD_IMAGES);
                validFiles.forEach(file => {
                    // 校验文件类型（前端二次校验，避免无效文件）
                    if (!file.type.startsWith('image/')) return;

                    const reader = new FileReader();
                    reader.onload = (readerEvent) => {
                        // 创建预览缩略图
                        const previewItem = document.createElement('div');
                        previewItem.className = 'relative w-24 h-24 rounded-md overflow-hidden border-2 border-primary/30';
                        
                        const img = document.createElement('img');
                        img.src = readerEvent.target.result;
                        img.alt = '图片预览';
                        img.className = 'w-full h-full object-cover';
                        
                        // 新增：删除预览图按钮
                        const deleteBtn = document.createElement('button');
                        deleteBtn.className = 'absolute top-1 right-1 bg-black bg-opacity-50 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-opacity-70 transition-colors';
                        deleteBtn.innerHTML = '<i class="fa fa-times"></i>';
                        deleteBtn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            previewItem.remove();
                            // 重置file输入（可选：复杂逻辑，此处简化为清空预览）
                            if (imagePreview.children.length === 0) {
                                imageUpload.value = '';
                                imagePreview.classList.add('hidden');
                            }
                        });
                        
                        previewItem.appendChild(img);
                        previewItem.appendChild(deleteBtn);
                        imagePreview.appendChild(previewItem);
                    };
                    reader.readAsDataURL(file);
                });

                imagePreview.classList.remove('hidden');  // 显示预览区
            });
        }

        // -------------------------- 新增：2. 高清图预览模态框逻辑 --------------------------
        // 关闭模态框
        if (closePreviewModal) {
            closePreviewModal.addEventListener('click', () => {
                imagePreviewModal.classList.add('hidden');
                previewImage.src = '';
            });
        }
        // 点击模态框背景关闭
        if (imagePreviewModal) {
            imagePreviewModal.addEventListener('click', (e) => {
                if (e.target === imagePreviewModal) {
                    imagePreviewModal.classList.add('hidden');
                    previewImage.src = '';
                }
            });
        }
        // 键盘ESC关闭
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !imagePreviewModal.classList.contains('hidden')) {
                imagePreviewModal.classList.add('hidden');
                previewImage.src = '';
            }
        });

        // -------------------------- 改造：3. 评论提交逻辑（从JSON改为FormData） --------------------------
        async function handleCommentSubmit(e) {
            e.preventDefault();
            
            if (!currentUserId) {
                return showNotification('请先登录后再发表评论', 'warning');
            }

            const contentInput = document.getElementById('content');
            const parentIdInput = document.getElementById('parentId');
            const content = contentInput.value.trim();
            
            if (!content) {
                return showNotification('请输入评论内容', 'warning');
            }

            // -------------------------- 关键改造：用FormData传递文字+图片 --------------------------
            const formData = new FormData();
            formData.append('content', content);  // 评论文字
            if (parentIdInput.value) {
                formData.append('parent_id', parentIdInput.value);  // 父评论ID（回复用）
            }
            // 添加选中的图片（如果有）
            if (imageUpload.files && imageUpload.files.length > 0) {
                const validFiles = Array.from(imageUpload.files).slice(0, MAX_UPLOAD_IMAGES);
                validFiles.forEach(file => {
                    formData.append('images', file);  // 后端接收的参数名：images（与File(...)对应）
                });
            }

            try {
                showLoading();
                
                const response = await fetch(`${API_BASE_URL}/comments`, {
                    method: 'POST',
                    // 注意：FormData不需要设置Content-Type，浏览器会自动处理
                    body: formData,
                    credentials: 'include'  // 携带登录会话
                });

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.detail || '提交失败');
                }

                // 提交成功：重置表单+重新加载评论
                commentForm.reset();
                imageUpload.value = '';  // 清空图片选择
                imagePreview.innerHTML = '';
                imagePreview.classList.add('hidden');

                // 新增：重置文件选择文本
                fileSelectedText.textContent = '未选择文件'; 

                parentIdInput.value = '';
                loadComments();  // 重新加载评论列表（含新评论的缩略图）
                showNotification(parentIdInput.value ? '回复成功！' : '评论发表成功！', 'success');

            } catch (error) {
                console.error('提交评论出错:', error);
                showNotification(error.message || '网络异常，请稍后重试', 'error');
            } finally {
                hideLoading();
            }
        }

        // -------------------------- 改造：4. 渲染评论时添加缩略图显示 --------------------------
        function createCommentElement(comment, allComments) {
            const div = document.createElement('div');
            div.className = 'bg-white rounded-xl p-6 comment-shadow transition-all duration-300 hover:shadow-lg';
            div.dataset.id = comment.id;

            // 原有逻辑：作者信息、时间、操作按钮...（不变）
            const isTopLevel = comment.parent_id === null;
            const isAuthor = currentUserId === comment.author_id;
            const formattedDate = new Date(comment.created_at).toLocaleString('zh-CN', {
                year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'
            });
            const formattedContent = comment.content.replace(/\n/g, '<br>');

            // -------------------------- 新增：渲染缩略图（如果有图片） --------------------------
            let imageHtml = '';
            if (comment.thumbnail_urls && comment.thumbnail_urls.length > 0) {
                imageHtml = `
                    <div class="mt-3 flex flex-wrap gap-3">
                        ${comment.thumbnail_urls.map((thumbUrl, index) => {
                            const originalUrl = comment.image_urls[index];  // 对应原图URL
                            return `
                                <div class="w-24 h-24 rounded-md overflow-hidden border border-gray-200 cursor-pointer hover:border-primary transition-colors">
                                    <img 
                                        src="${thumbUrl}" 
                                        alt="评论图片${index+1}" 
                                        class="w-full h-full object-cover"
                                        data-original="${originalUrl}"  // 存储原图URL
                                        onclick="openImagePreview('${originalUrl}')"  // 点击触发预览
                                    >
                                </div>
                            `;
                        }).join('')}
                    </div>
                `;
            }

            // 构建评论HTML（原有逻辑+新增imageHtml）
            div.innerHTML = `
                <div class="flex justify-between items-start mb-3">
                    <!-- 原有：作者头像、名称、时间 -->
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold mr-3">
                            ${comment.author.charAt(0).toUpperCase()}
                        </div>
                        <div>
                            <h4 class="font-medium text-gray-800">${comment.author}</h4>
                            <p class="text-sm text-neutral">${formattedDate}</p>
                        </div>
                    </div>
                    <!-- 原有：回复、编辑、删除按钮 -->
                    <div class="flex space-x-2">
                        <button class="reply-btn text-neutral hover:text-primary p-1.5 rounded-full hover:bg-gray-100 transition-colors"
                                data-comment-id="${comment.id}"
                                data-author-name="${comment.author}"
                                title="回复">
                            <i class="fa fa-reply"></i>
                        </button>
                        ${isTopLevel && isAuthor ? `<button class="edit-btn text-neutral hover:text-blue-500 p-1.5 rounded-full hover:bg-gray-100 transition-colors" data-comment-id="${comment.id}" title="修改"><i class="fa fa-pencil"></i></button>` : ''}
                        ${isAuthor ? `<button class="delete-btn text-neutral hover:text-red-500 p-1.5 rounded-full hover:bg-gray-100 transition-colors" data-comment-id="${comment.id}" data-author-id="${comment.author_id}" title="删除"><i class="fa fa-trash-o"></i></button>` : ''}
                    </div>
                </div>
                <!-- 原有：评论文字内容 -->
                <div class="mb-4">
                    <p class="text-gray-800">${formattedContent}</p>
                </div>
                <!-- 新增：缩略图显示 -->
                ${imageHtml}
                <!-- 原有：回复列表 -->
                <div class="replies pl-6 mt-4 space-y-4"></div>
            `;

            // 原有：添加回复列表（不变）
            const repliesContainer = div.querySelector('.replies');
            const replies = allComments.filter(c => c.parent_id === comment.id);
            replies.forEach(reply => {
                const replyElement = createCommentElement(reply, allComments);
                replyElement.classList.add('reply-line');
                repliesContainer.appendChild(replyElement);
            });

            return div;
        }

        // -------------------------- 新增：打开图片预览模态框的函数 --------------------------
        function openImagePreview(originalUrl) {
            previewImage.src = originalUrl;
            imagePreviewModal.classList.remove('hidden');
        }

        // -------------------------- 原有：页面加载初始化（不变） --------------------------
        document.addEventListener('DOMContentLoaded', () => {
            loadComments();
            setupEventListeners();
        });


        // 初始化编辑图片上传控件
        if (editImageUpload && editFileSelectedText) {
            editImageUpload.addEventListener('change', (e) => {
                const files = e.target.files;
                if (files && files.length > 0) {
                    const filenames = Array.from(files).map(f => f.name).join(', ');
                    editFileSelectedText.textContent = `已选择：${filenames}`;
                    previewEditImages(files);
                } else {
                    editFileSelectedText.textContent = '未选择文件';
                }
            });
        }

//         // 预览编辑时选择的图片
//         function previewEditImages(files) {
//             const validFiles = Array.from(files).slice(0, MAX_UPLOAD_IMAGES);
            
//             validFiles.forEach(file => {
//                 if (!file.type.startsWith('image/')) return;

//                 const reader = new FileReader();
//                 reader.onload = (readerEvent) => {
//                     const previewItem = document.createElement('div');
//                     previewItem.className = 'relative w-24 h-24 rounded-md overflow-hidden border-2 border-primary/30';
//                     previewItem.dataset.type = 'new'; // 标记为新上传的图片
                    
//                     const img = document.createElement('img');
//                     img.src = readerEvent.target.result;
//                     img.className = 'w-full h-full object-cover';
                    
//                     const deleteBtn = document.createElement('button');
//                     deleteBtn.className = 'absolute top-1 right-1 bg-black bg-opacity-50 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-opacity-70 transition-colors';
//                     deleteBtn.innerHTML = '<i class="fa fa-times"></i>';
//                     deleteBtn.addEventListener('click', (e) => {
//                         e.stopPropagation();
//                         previewItem.remove();
//                         updateEditFileText();
//                     });
                    
//                     previewItem.appendChild(img);
//                     previewItem.appendChild(deleteBtn);
//                     editImagePreview.appendChild(previewItem);
//                 };
//                 reader.readAsDataURL(file);
//             });
//         }

// //         // 预览编辑时选择的图片
// //         function previewEditImages(files) {
// //     // 关键修复：先移除所有之前添加的新图预览（保留原有图片）
// //     const existingNewImages = editImagePreview.querySelectorAll('[data-type="new"]');
// //     existingNewImages.forEach(el => el.remove());

// //     // 再添加本次选择的新图预览
// //     Array.from(files).forEach(file => {
// //         const reader = new FileReader();
// //         reader.onload = function(e) {
// //             const previewItem = document.createElement('div');
// //             previewItem.className = 'relative w-24 h-24 rounded-md overflow-hidden border-2 border-gray-300';
// //             previewItem.dataset.type = 'new'; // 标记为新添加的图片

// //             const img = document.createElement('img');
// //             img.src = e.target.result;
// //             img.className = 'w-full h-full object-cover';

// //             const deleteBtn = document.createElement('button');
// //             deleteBtn.className = 'absolute top-1 right-1 bg-black bg-opacity-50 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-opacity-70 transition-colors';
// //             deleteBtn.innerHTML = '<i class="fa fa-times"></i>';
// //             deleteBtn.addEventListener('click', (e) => {
// //                 e.stopPropagation();
// //                 previewItem.remove();
// //                 // 更新文件选择文本
// //                 updateEditFileText();
// //             });

// //             previewItem.appendChild(img);
// //             previewItem.appendChild(deleteBtn);
// //             editImagePreview.appendChild(previewItem);
// //         };
// //         reader.readAsDataURL(file);
// //     });
// //     // 更新文件选择文本
// //     updateEditFileText();
// // }

//         // 更新编辑时的文件选择文本
//         function updateEditFileText() {
//             const newImagesCount = editImagePreview.querySelectorAll('[data-type="new"]').length;
//             if (newImagesCount > 0) {
//                 editFileSelectedText.textContent = `已选择：${newImagesCount}张图片`;
//             } else {
//                 editFileSelectedText.textContent = '未选择文件';
//             }
//         }
    

// 1. 修复编辑时图片选择逻辑
    editImageUpload.addEventListener('change', (e) => {
        const newFiles = Array.from(e.target.files);
        // 计算可添加的文件数量
        const remainingSlots = MAX_UPLOAD_IMAGES - editNewFiles.length;
        if (remainingSlots <= 0) {
            showNotification(`最多只能上传${MAX_UPLOAD_IMAGES}张图片`, 'warning');
            return;
        }
        
        // 只添加不超过剩余数量的文件
        const filesToAdd = newFiles.slice(0, remainingSlots);
        editNewFiles = [...editNewFiles, ...filesToAdd];
        
        // 更新预览
        filesToAdd.forEach(file => {
            addEditImagePreview(file, 'new');
        });
        updateEditFileText();
        
        // 清空input值，允许重复选择同一文件
        e.target.value = '';
    });

    // 2. 添加预览图片的辅助函数
    function addEditImagePreview(item, type, url = null) {
        const previewItem = document.createElement('div');
        previewItem.className = 'relative w-24 h-24 rounded-md overflow-hidden border-2 border-gray-300';
        previewItem.dataset.type = type;
        
        if (type === 'new') {
            // 新上传的图片
            const file = item;
            const reader = new FileReader();
            reader.onload = (e) => {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'w-full h-full object-cover';
                previewItem.appendChild(img);
            };
            reader.readAsDataURL(file);
            previewItem.dataset.index = editNewFiles.indexOf(file);
        } else {
            // 已存在的图片
            const img = document.createElement('img');
            img.src = url;
            img.className = 'w-full h-full object-cover';
            previewItem.appendChild(img);
            previewItem.dataset.url = item;
        }
        
        // 添加删除按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'absolute top-1 right-1 bg-black bg-opacity-50 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-opacity-70 transition-colors';
        deleteBtn.innerHTML = '<i class="fa fa-times"></i>';
        deleteBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            if (type === 'new') {
                // 从新文件列表中删除
                const index = parseInt(previewItem.dataset.index);
                editNewFiles = editNewFiles.filter((_, i) => i !== index);
                // 更新剩余文件的索引
                updateEditFileIndices();
            } else {
                // 已存在的图片处理（原逻辑保留）
                deletedImageUrls.push(previewItem.dataset.url);
            }
            previewItem.remove();
            updateEditFileText();
        });
        
        previewItem.appendChild(deleteBtn);
        editImagePreview.appendChild(previewItem);
    }

    // 3. 更新新文件索引的辅助函数
    function updateEditFileIndices() {
        const newPreviews = editImagePreview.querySelectorAll('[data-type="new"]');
        newPreviews.forEach((preview, index) => {
            preview.dataset.index = index;
        });
    }

    // 4. 更新文件选择文本的辅助函数
    function updateEditFileText() {
        const totalFiles = editNewFiles.length + editImagePreview.querySelectorAll('[data-type="existing"]').length;
        editFileSelectedText.textContent = totalFiles > 0 ? 
            `已选择 ${totalFiles} 个文件` : '未选择文件';
    }

    // 5. 修复编辑表单提交逻辑
    document.getElementById('editForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const commentId = document.getElementById('editCommentId').value;
        const content = document.getElementById('editContent').value.trim();
        
        if (!content) {
            return showNotification('请输入评论内容', 'warning');
        }
        
        try {
            showLoading();
            
            const formData = new FormData();
            formData.append('content', content);
            
            // 处理删除的图片
            deletedImageUrls.forEach(url => {
                formData.append('deleted_images', url);
            });
            
            // 处理新上传的图片（只添加当前列表中的文件）
            editNewFiles.forEach(file => {
                formData.append('images', file);
            });

            const response = await fetch(`${API_BASE_URL}/comments/${commentId}`, {
                method: 'PUT',
                body: formData,
                credentials: 'include'
            });
            
            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || '修改失败');
            }
            
            // 重置状态
            loadComments();
            document.getElementById('editModal').classList.add('hidden');
            document.getElementById('editForm').reset();
            editImagePreview.innerHTML = '';
            editNewFiles = [];
            deletedImageUrls = [];
            showNotification('评论修改成功', 'success');
            
        } catch (error) {
            console.error('修改评论时出错:', error);
            showNotification(error.message || '修改失败，请稍后重试', 'error');
        } finally {
            hideLoading();
        }
    });

    // 6. 修复编辑按钮点击时的初始化逻辑
    commentsContainer.addEventListener('click', (e) => {
        const editBtn = e.target.closest('.edit-btn');
        if (editBtn) {
            // 重置新文件列表
            editNewFiles = [];
            // 清空预览区
            editImagePreview.innerHTML = '';
            // 其他原有逻辑...
            
            const commentId = editBtn.dataset.commentId;
            const commentElement = document.querySelector(`[data-id="${commentId}"]`);
            const contentElement = commentElement.querySelector('p.text-gray-800');
            const originalContent = contentElement.innerHTML.replace(/<br>/g, '\n');
            
            document.getElementById('editCommentId').value = commentId;
            document.getElementById('editContent').value = originalContent;
            deletedImageUrls = [];
            
            // 加载现有图片
            const comment = comments.find(c => c.id == commentId);
            if (comment && comment.image_urls && comment.image_urls.length > 0) {
                comment.image_urls.forEach((imgUrl, index) => {
                    const thumbUrl = comment.thumbnail_urls[index];
                    addEditImagePreview(imgUrl, 'existing', thumbUrl);
                });
            }
            
            updateEditFileText();
            document.getElementById('editModal').classList.remove('hidden');
        }
    });
    </script>
</body>
</html>